package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"strconv"
	"time"
	"wxcloudrun-golang/config"
	"wxcloudrun-golang/models"
)

type UserController struct {
	BaseController
}
type WxChatLogin struct {
	Code string `json:"code"`
}

type WXLoginResp struct {
	OpenId     string `json:"openid"`
	SessionKey string `json:"session_key"`
}
type LoginResp struct {
	Id     int    `json:"id"`
	OpenId string `json:"open_id"`
	Token  string `json:"token"`
}

func (con UserController) Login(c *gin.Context) {
	var wxChatLogin WxChatLogin
	if err := c.BindJSON(&wxChatLogin); err != nil {
		return
	}
	fmt.Println(wxChatLogin.Code)
	Openid, _ := getOpenid(wxChatLogin.Code)
	fmt.Println(Openid)
	if Openid == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "登录失败"})
	}
	var user models.Users
	result := models.DB.Where("open_id = ?", Openid).First(&user)
	if result.Error != nil {
		users := models.Users{
			OpenId: Openid,
			Role:   "0",
		}
		if err := users.Insert(); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败请稍后再试"})
			return
		}
		var user1 models.Users
		result1 := models.DB.Where("open_id = ?", Openid).First(&user1)
		if result1.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "系统出现异常"})
		}
		signedToken, _ := GenerateToken(strconv.Itoa(user1.Id))
		response := LoginResp{
			Id:     user1.Id,
			OpenId: user1.OpenId,
			Token:  signedToken,
		}
		c.JSON(http.StatusOK, gin.H{"data": response})
	}
	signedToken, _ := GenerateToken(strconv.Itoa(user.Id))
	response := LoginResp{
		Id:     user.Id,
		OpenId: user.OpenId,
		Token:  signedToken,
	}
	c.JSON(http.StatusOK, gin.H{"data": response})
}

// getOpenid 发送请求到微信API获取openid
func getOpenid(code string) (string, error) {

	var login config.WeChatProperties
	login.AppID = "wxcdc0dcfab46b1440"
	login.AppSecret = "bc5c8f9b396bf567e8ee50bf8b03674d"
	// 构造请求URL
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?"+
		"appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		login.AppID, login.AppSecret, code)

	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// 解析JSON响应
	var wxResp WXLoginResp
	if err := json.Unmarshal(body, &wxResp); err != nil {
		return "", err
	}
	fmt.Println(wxResp)
	// 检查微信API返回的错误码
	// 返回openid
	return wxResp.OpenId, nil
}
func GenerateToken(userID string) (string, error) {
	issuer := "lostfound"
	expiry := time.Now().Add(time.Hour * 10).Unix()

	claims := jwt.MapClaims{
		"iss":    issuer,
		"exp":    expiry,
		"userid": userID, // 添加用户ID声明
	}

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	key := []byte("lostfound") // 签名密钥
	signedToken, err := token.SignedString(key)
	if err != nil {
		return "", fmt.Errorf("error signing token: %w", err)
	}

	return signedToken, nil
}
